package info.xinfu.carban.base;


import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.graphics.Bitmap;
import android.media.SoundPool;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.webkit.CookieManager;
import android.webkit.CookieSyncManager;
import android.webkit.JsResult;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.TextView;

import info.xinfu.carban.R;
import com.hui.util.log.LogUtils;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.cookie.CookieJarImpl;
import com.zhy.http.okhttp.cookie.store.CookieStore;

import java.util.List;

import okhttp3.Cookie;

/**
 * Created by clare on 2018/5/22.
 */
public class WebViewActivity  extends Activity implements OnClickListener {
    private WebView webView;
    private String urlParameter = "";
    private TextView mTitleTextView;
    private String url_remote;
    private String url_data;
    private SoundPool mSoundPool;
    private int mSoundPoolLoad;
    private String inType;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.webview_activity);
        Bundle bdl = getIntent().getExtras();
        url_remote = bdl.getString("url_remote", "www.xinfu.info");
        url_data = bdl.getString("url_data", "www.xinfu.info");
        inType = bdl.getString("inType", "");
        // TODO: 2017/11/16 需要共享cookies啦
        /**
         * 获取okhttpclient session
         */
        CookieJarImpl cookieJar = (CookieJarImpl) OkHttpUtils.getInstance().getOkHttpClient().cookieJar();
        CookieStore cookieStore = cookieJar.getCookieStore();
        List<Cookie> cookies = cookieStore.getCookies();
        if (cookies != null && cookies.size() > 0) {
            for (int i = 0; i < cookies.size(); i++) {
                Cookie cookie = cookies.get(0);
//                if(cookie.name().equalsIgnoreCase("jsessionid")){
                String cookieString = cookie.name() + "=" + cookie.value() + ";domain=" + cookie.domain();
                LogUtils.w("cookieString: " + cookieString);
                //webview set cookie，在loadUrl()之前放webview
                CookieManager cookieManager = CookieManager.getInstance();
                cookieManager.setCookie(url_remote, cookieString);
                CookieSyncManager.getInstance().sync();
//                }
            }
        }
        initWebView();
        //刷新界面，加载webview
        refresh();


    }



    private void refresh() {
 /*       if(isNetworkConnected()){
            findView(R.id.webview1).setVisibility(View.VISIBLE);
            reloadUtil.showDataView();
            initWebView();
        }else{
            findView(R.id.webview1).setVisibility(View.GONE);
            reloadUtil.showReload();
        }*/

    }

    private void initWebView() {
        webView = (WebView) findViewById(R.id.web_base);

        //初始化webview
        //启用支持javascript
        WebSettings settings = webView.getSettings();
        settings.setJavaScriptEnabled(true);//支持javaScript
        settings.setDefaultTextEncodingName("utf-8");//设置网页默认编码
        settings.setJavaScriptCanOpenWindowsAutomatically(true);
        Log.d("TAG", "url:"+url_remote);
        //post请求(使用键值对形式，格式与get请求一样，key=value,多个用&连接)
        urlParameter = "JSONpriKey=" +urlParameter;
//        webView.postUrl(url_remote, EncodingUtils.getBytes(url_data, "UTF-8"));
//	        webView.loadUrl(url);//get
        webView.setWebChromeClient(new MyWebChromeClient());// 设置浏览器可弹窗
        //覆盖WebView默认使用第三方或系统默认浏览器打开网页的行为，使网页用WebView打开
        webView.setWebViewClient(new WebViewClient(){
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                if (url.startsWith("http:") || url.startsWith("https:")) {
                    if (url.contains("scanAppOut")) {
                        finish();
                        return false;
                    } else if (url.contains("scanAppSuccess")) {
                        finish();
                        return false;
                    } else if (url.contains("scanAppRefresh")) {
                        //重新扫描--退到设置，重新请求
//                        EventBus.getDefault().post(new Event_refresh_scanCode(true));
                        finish();
                        return false;
                    }
                    LogUtils.w(url);
                    view.loadUrl(url);
                }
                return true;
            }
            @Override
            public void onPageStarted(WebView view, String url,
                                      Bitmap favicon) {


                super.onPageStarted(view, url, favicon);
            }


            @Override
            public void onPageFinished(WebView view, String url) {
                super.onPageFinished(view, url);

            }

        });



    }



    @Override
    public boolean onKeyDown(int keyCode,  KeyEvent event) {
        if(keyCode == KeyEvent.KEYCODE_BACK && webView !=null && webView.canGoBack()){
            webView.goBack();
            return true;
        }

        return super.onKeyDown(keyCode, event);
    }

    @Override
    public void onClick(View v) {

    }


    /**
     * 浏览器可弹窗
     *
     * @author Administrator
     *
     */
    final class MyWebChromeClient extends WebChromeClient {
        @Override
        public boolean onJsConfirm(WebView view, String url, String message,
                                   final JsResult result) {
            new AlertDialog.Builder(WebViewActivity.this)
                    .setTitle("App Titler")
                    .setMessage(message)
                    .setPositiveButton(android.R.string.ok,
                            new DialogInterface.OnClickListener() {
                                public void onClick(DialogInterface dialog,
                                                    int which) {
                                    result.confirm();
                                }
                            })
                    .setNegativeButton(android.R.string.cancel,
                            new DialogInterface.OnClickListener() {
                                public void onClick(DialogInterface dialog,
                                                    int which) {
                                    result.cancel();
                                }
                            }).create().show();

            return true;
        }
    }
}